<template>
  <el-dialog v-model="visible" title="导出中心" width="950" draggable :close-on-click-modal="false" :close-on-press-escape="false" @close="close">
    <div class="flex">
      <div class="left flex-1 mr-5">
        <div class="font-medium text-black">字段列表</div>
        <div style="width: 432px">
          <el-table :data="export_field" height="600" style="width: 100%" highlight-current-row @selection-change="handleSelectionChange" border ref="tableRef">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="field_name" label="字段" />
            <el-table-column prop="opearn" label="排序" width="120">
              <template #default="scope">
                <el-link type="primary" :underline="false" @click="moveUp(scope.$index, scope.row)">上移</el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" :underline="false" @click="moveDown(scope.$index, scope.row)">下移</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="right flex-1">
        <div class="flex items-center mb-[6px]" v-if="importBtnSlot">
          <el-tag type="danger">提示:</el-tag>
          <svg-icon icon-class="hint_line01"></svg-icon>导出结果在 <el-link type="primary" :underline="false" @click="navPersonal">个人中心</el-link> 查看
        </div>

        <div class="flex justify-between items-end mb-4">
          <slot v-if="importBtnSlot" :name="importBtnSlot"></slot>
          <template v-else>
            <el-button type="primary" @click="handleImport">导出</el-button>

            <div class="flex text-xs text-gray-400 ml-5">
              <svg-icon icon-class="hint_line01"></svg-icon>导出结果在 <el-link type="primary" :underline="false" @click="navPersonal">个人中心</el-link> 查看
            </div>
          </template>
        </div>
        <div class="flex items-center mb-2"><el-input v-model="exportName" class="w-full" placeholder="请输入名称" /><el-button type="primary" plain @click="saveTemplate">保存模版</el-button></div>
        <el-table :data="templates" style="width: 100%" highlight-current-row border @row-click="tabRowClick">
          <el-table-column prop="name" label="名称" width="300">
            <template #default="{ row, $index }">
              <div class="flex">
                <div class="flex-1">
                  <el-link type="primary" :underline="false" @click="selectField(row, $index)">{{ row.name }}</el-link>
                </div>
                <el-link type="primary" v-if="handleTemplateRow.index == $index && handleTemplateRow.change" @click="updateTemplate(row)">保存</el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="opearn" label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="exportRow(scope.row)">导出</el-button>
              <template v-if="scope.row.creator_id == user_id">
                <el-divider direction="vertical" />
                <el-button type="danger" link @click="exportDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <!-- <div class="flex justify-center"> -->
      <el-button @click="close">关闭</el-button>
      <!-- </div> -->
    </template>
  </el-dialog>
</template>
<script setup name="DerivedCenter">
import { reactive, toRefs, getCurrentInstance, onMounted } from "vue"
import { getExportConfig, exportRord, exporttpl, exportTemplateUpdate, exportTemplateOne, exportTemplateDelete } from "@/api/index"
import { ElMessage } from "element-plus"
import action from "@/utils/action.js"

const { proxy } = getCurrentInstance()
const emits = defineEmits(["query", "callback"])
const props = defineProps({})

const data = reactive({
  visible: false,
  form: {
    config_id: null,
    config_name: null,
    condition: null,
  },

  export_field: [], // 字段列表
  multipleSelection: [], // 字段列表 选项

  user_id: "", // 当前操作人
  tag_name: "", // 导出模块 key

  exportName: "", // 保存 导出模板名称
  templates: [], // 导出模板 列表
})

const tagNamesOpt = ref({})
const { visible, form, tag_name, user_id, export_field, multipleSelection, exportName, templates } = toRefs(data)
const importBtnSlot = ref("")
const open = async (item) => {
  visible.value = true
  form.value.condition = item.condition
  tag_name.value = item.tag_name
  // 导出按钮
  importBtnSlot.value = item.importBtnSlot
  try {
    await getTemplate()
    // getTemplateConfig(item.tag_name)
  } catch (err) {
    console.warn(err)
  }
}
const getTemplate = async () => {
  try {
    const res = await getTemplateConfig(tag_name.value)
    form.value.config_id = res.data.config_id // 导出模块 id
    form.value.config_name = res.data.config_name // 导出模块 名称
    templates.value = res.data.templates // 模板列表
    export_field.value = res.data.export_field // 字段列表
  } catch (e) {
    throw Error(e)
  }
}

const tableRef = ref()

// 导出模板 当前操作行
const handleTemplateRow = ref({
  index: "",
  change: false,
})

const tabRowClick = (row, column, event) => {
  // console.log(row, column, event);
}
// 选择导出模板
const selectField = (item, index) => {
  tableRef.value.clearSelection()
  export_field.value
    .filter((v) => item.fields.includes(v.field_key))
    .forEach((val) => {
      tableRef.value.toggleRowSelection(val, true)
    })
  let fields = [...item.fields]
  fields.reverse()
  export_field.value = export_field.value.sort((a, b) => {
    return fields.indexOf(b.field_key) - fields.indexOf(a.field_key)
  })
  handleTemplateRow.value.index = String(index)
  handleTemplateRow.value.change = false
}

// 字段列表 选项变动
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  if (handleTemplateRow.value.index) {
    handleTemplateRow.value.change = true
  }
}
// 字段列表 上移
const moveUp = (index, row) => {
  if (index > 0) {
    if (handleTemplateRow.value.index) {
      handleTemplateRow.value.change = true
    }
    const upDate = export_field.value[index - 1]
    export_field.value.splice(index - 1, 1)
    export_field.value.splice(index, 0, upDate)
  } else {
    ElMessage.error("已经是第一条，不可上移")
  }
}
// 字段列表 下移
const moveDown = (index, row) => {
  if (index + 1 === export_field.value.length) {
    ElMessage.error("已经是最后一条，不可下移")
  } else {
    if (handleTemplateRow.value.index) {
      handleTemplateRow.value.change = true
    }
    const downDate = export_field.value[index + 1]
    export_field.value.splice(index + 1, 1)
    export_field.value.splice(index, 0, downDate)
  }
}

const handleImport = async () => {
  if (multipleSelection.value.length == 0) {
    return ElMessage.error("至少勾选一条导出项")
  }
  let params = {
    ...form.value,
    fields: multipleSelection.value.map((i) => i.field_key),
    title: `${form.value.config_name}${window.userInfo.user.realname}`,
    module: tag_name.value,
  }
  try {
    const res = await exportRord(params)
    emits("callback")
    ElMessage.success(res.message)
  } catch (e) {
    throw Error(e)
  }
}

// 保存 导出模版
const saveTemplate = async () => {
  if (multipleSelection.value.length == 0) {
    return ElMessage.error("至少勾选一条导出项")
  }
  if (!exportName.value) {
    return ElMessage.error("请输入名称")
  }
  if (templates.value.find((v) => v.name == exportName.value)) {
    return ElMessage.error("保存模板的名称不可以重复")
  }
  const fields = multipleSelection.value.map((i) => i.field_key)

  try {
    const res = await exporttpl({
      config_id: form.value.config_id,
      name: exportName.value,
      fields,
    })
    ElMessage.success(res.data.message)
    getTemplate()
  } catch (e) {
    throw Error(e)
  }
}
// 编辑 导出模版
const updateTemplate = (row) => {
  if (multipleSelection.value.length == 0) {
    return ElMessage.error("至少勾选一条导出项")
  }

  let fields = multipleSelection.value.map((i) => i.field_key)
  let fieldSort = export_field.value.map((v) => v.field_key)
  fields = fields.sort((a, b) => {
    return fieldSort.indexOf(a) - fieldSort.indexOf(b)
  })
  let params = {
    id: row.tpl_id,
    name: row.name,
    fields: fields,
  }
  exportTemplateUpdate(params).then((res) => {
    getTemplate()
    ElMessage.success(res.data.message)
    handleTemplateRow.value.index = NaN
  })
}

// 导出模板 导出行配置
const tplId = ref("")
const exportRow = async (row) => {
  const title = row.name + window.userInfo.user.realname
  try {
    const res = await exportRord({
      tpl_id: row.tpl_id,
      ...form.value,
      title,
      fields: [],
      module: tag_name.value, // 导出模版  默认第一个
    })
    ElMessage.success(res.message)
    tplId.value = row.tpl_id
    emits("callback")
  } catch (e) {
    throw Error(e)
  }
}

const exportDelete = async (row) => {
  try {
    const res = await exportTemplateDelete(row.tpl_id)
    ElMessage.success(res.data.message)
    getTemplate()
  } catch (e) {
    throw Error(e)
  }
}

onMounted(() => {
  user_id.value = window.userInfo?.user?.user_id
})

const close = () => {
  exportName.value = ""
  handleTemplateRow.value.index = ""
  handleTemplateRow.value.change = false

  visible.value = false
}

// 获取 导出配置
const getTemplateConfig = async (tag_name) => {
  try {
    return await exportTemplateOne({ home_system: 3, tag_name: tag_name })
  } catch (e) {
    throw Error(e)
  }
}
// 组建外部调用导出
const outerExport = async (module, moduleName, type = "") => {
  console.log("组建外部调用导出")
  // if (!tplId.value && multipleSelection.value.length == 0) {
  //   return ElMessage.error("至少勾选一条导出项")
  // }
  let params = {
    ...form.value,
    fields: multipleSelection.value?.map((i) => i.field_key), //
    title: `${moduleName}${window.userInfo.user.realname}`,
    module,
  }
  // if (tplId.value) {
  //   params.tpl_id = tplId.value
  // } else {
  // params.fields = multipleSelection.value?.map((i) => i.field_key)
  // }
  let templateRes = await getTemplateConfig(module)
  params.config_id = templateRes.data.config_id
  if (type == "all") {
    params.fields = templateRes.data.export_field.map((i) => i.field_key)
  }
  try {
    const res = await exportRord(params)
    // ElMessage.success(res.message)
  } catch (e) {
    throw Error(e)
  }
}
// 跳转 个人中心
const navPersonal = async () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      path: "/user/profile",
      type: "push",
    },
  })
}
defineExpose({
  open,
  outerExport,
})
</script>
